import { message } from 'ant-design-vue'
import axios from 'axios'

import { useUserStore } from '@/store'

const ajax = axios.create({
  baseURL: import.meta.env.VITE_APP_API,
  timeout: 30000
})

ajax.interceptors.request.use(req => {
  const userStore = useUserStore()

  if (req.withToken !== false) {
    req.headers![userStore.tokenName] = userStore.token
  }
  return req
})

ajax.interceptors.response.use(
  res => {
    if (res.config.withResponse) {
      return res.data
    }
    if (res.data.code !== 20000) {
      if (res.data.code === 200) {
        const userStore = useUserStore()
        userStore.clear()

        message.error(res.data.message, 1, () => {
          location.reload()
        })

        return Promise.reject(res.data.message)
      } else {
        message.error(res.data.message || '未知错误', 1.5)
        return Promise.reject(res.data.message || '未知错误')
      }
    } else {
      return res.data.data
    }
  },
  err => {
    message.error(err.message, 1.5)
    return Promise.reject(err.message)
  }
)

export { ajax }
